﻿using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Controls;
using System.Collections.Generic;
using VMuktiGrid.Buddy;
using VMuktiGrid.CustomMenu;
using System;
using VMukti.Presentation.Controls;
using VMukti.Business.CommonDataContracts;
using VMuktiAPI;

namespace VMuktiGrid.ctlTab
{
    [TemplatePart(Name = "PART_CloseButton", Type = typeof(ButtonBase))]
    public class TabItem : System.Windows.Controls.TabItem
    {
        private List<string> buddyList = new List<string>();

        public string ObjectType = "";
        public int ObjectID = int.MinValue;
        private bool _IsSaved = false;

        public bool IsSaved
        {
            get { return _IsSaved; }
            set 
            { 
                _IsSaved = value;
                try
                {
                    ((VMuktiGrid.ctlPage.TabItem)((VMuktiGrid.ctlTab.TabControl)this.Parent).Parent).IsSaved = value;
                }
                catch { }
            }
        }

        public int OwnerTabIndex = int.MinValue;

        static TabItem()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(ctlTab.TabItem), new FrameworkPropertyMetadata(typeof(ctlTab.TabItem)));
        }

        /// <summary>
        /// Provides a place to display an Icon on the TabItem and on the DropDown Context Menu
        /// </summary>
        public object Icon
        {
            get { return (object)GetValue(IconProperty); }
            set { SetValue(IconProperty, value); }
        }
        public static readonly DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(object), typeof(TabItem), new UIPropertyMetadata(null));

        /// <summary>
        /// Allow the TabItem to be Deleted by the end user
        /// </summary>
        public bool AllowDelete
        {
            get { return (bool)GetValue(AllowDeleteProperty); }
            set { SetValue(AllowDeleteProperty, value); }
        }
        public static readonly DependencyProperty AllowDeleteProperty = DependencyProperty.Register("AllowDelete", typeof(bool), typeof(TabItem), new UIPropertyMetadata(true));

        /// <summary>
        /// OnApplyTemplate override
        /// </summary>
        public override void OnApplyTemplate()
        {
            try
            {
                base.OnApplyTemplate();

                ((VMuktiGrid.ctlPage.TabItem)((VMuktiGrid.ctlTab.TabControl)this.Parent).Parent).IsSaved = _IsSaved;

                this.AllowDrop = true;

                // wire up the CloseButton's Click event if the button exists
                ButtonBase button = this.Template.FindName("PART_CloseButton", this) as ButtonBase;
                if (button != null)
                {
                    button.Click += delegate
                    {
                        // get the parent tabcontrol 
                        TabControl tc = Helper.FindParentControl<TabControl>(this);
                        if (tc == null) return;

                        // remove this tabitem from the parent tabcontrol
                        tc.RemoveItem(this);
                    };
                }

                if (buddyList.Count > 0)
                {
                    for (int i = 0; i < buddyList.Count; i++)
                    {
                        ((ctlMenu)this.Template.FindName("objMenu", this)).AddBuddy(buddyList[i]);
                        ((VMuktiGrid.CustomGrid.ctlGrid)this.Content).AddBuddy(buddyList[i]);
                        //((ctlBuddyList)this.Template.FindName("objBuddyList", this)).AddBuddy(buddyList[i]);
                    }
                    buddyList.Clear();
                }
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "OnApplyTemplate()--:--tab->TabItem.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        /// <summary>
        /// OnMouseEnter, Create and Display a Tooltip if the Header is cropped
        /// </summary>
        /// <param name="e"></param>
        protected override void OnMouseEnter(System.Windows.Input.MouseEventArgs e)
        {
            try
            {
                base.OnMouseEnter(e);

                //this.ToolTip = Helper.CloneElement(Header);
                e.Handled = true;
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "OnMouseEnter()--:--tab->TabItem.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        /// <summary>
        /// OnMouseLeave, remove the tooltip
        /// </summary>
        /// <param name="e"></param>
        protected override void OnMouseLeave(System.Windows.Input.MouseEventArgs e)
        {
            base.OnMouseLeave(e);

            //this.ToolTip = null;
            e.Handled = true;
        }

        public bool AddBuddy(string strBuddyName)
        {
            try
            {
                if (((ctlMenu)this.Template.FindName("objMenu", this)) != null)
                {
                    ((VMuktiGrid.CustomGrid.ctlGrid)this.Content).AddBuddy(strBuddyName);
                    return ((ctlMenu)this.Template.FindName("objMenu", this)).AddBuddy(strBuddyName);
                }
                else
                {
                    buddyList.Add(strBuddyName);
                    return true;
                }
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "AddBuddy()--:--tab->TabItem.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
                return false;
            }
        }

        public void Save(int pageID)
        {
            try
            {
                if (!IsSaved)
                {
                    if (ObjectID == int.MinValue)
                    {
                        ObjectID = (new VMukti.Business.VMuktiGrid.ClsTab()).Add_Tab(-1, pageID, ((VMuktiGrid.ctlTab.TabControl)this.Parent).Items.IndexOf(this) + 1, ((ctlPgTabHeader)this.Header).Title, "", VMuktiAPI.VMuktiInfo.CurrentPeer.ID, ((VMuktiGrid.CustomGrid.ctlGrid)this.Content).LeftPanelContainer.ActualWidth, ((VMuktiGrid.CustomGrid.ctlGrid)this.Content).CentralPanelContainer.ActualWidth, ((VMuktiGrid.CustomGrid.ctlGrid)this.Content).RightPanelContainer.ActualWidth);
                    }
                    else
                    {
                        (new VMukti.Business.VMuktiGrid.ClsTab()).Add_Tab(ObjectID, pageID, ((VMuktiGrid.ctlTab.TabControl)this.Parent).Items.IndexOf(this) + 1, ((ctlPgTabHeader)this.Header).Title, "", VMuktiAPI.VMuktiInfo.CurrentPeer.ID, ((VMuktiGrid.CustomGrid.ctlGrid)this.Content).LeftPanelContainer.ActualWidth, ((VMuktiGrid.CustomGrid.ctlGrid)this.Content).CentralPanelContainer.ActualWidth, ((VMuktiGrid.CustomGrid.ctlGrid)this.Content).RightPanelContainer.ActualWidth);
                    }
                    ((VMuktiGrid.CustomGrid.ctlGrid)this.Content).Save(ObjectID);
                    IsSaved = true;
                }
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "Save()--:--tab->TabItem.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        public void Delete()
        {
            try
            {
                if (ObjectID == int.MinValue)
                {
                    try
                    {
                        ((VMuktiGrid.ctlTab.TabControl)this.Parent).Items.Remove(this);
                    }
                    catch (Exception exp)
                    {
                        MessageBox.Show(exp.Message);
                    }
                }
                else
                {
                    try
                    {
                        (new VMukti.Business.VMuktiGrid.ClsTab()).Remove_Tab(ObjectID);
                        ((VMuktiGrid.ctlTab.TabControl)this.Parent).Items.Remove(this);
                        VMukti.Business.VMuktiGrid.ClsPod.Remove_PodTab(ObjectID);
                    }
                    catch (Exception exp)
                    {
                        MessageBox.Show(exp.Message);
                    }

                }
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "Delete()--:--tab->TabItem.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        public void Close()
        {
            try
            {
                ((VMuktiGrid.ctlTab.TabControl)this.Parent).Items.Remove(this);
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "Close()--:--tab->TabItem.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }
    }
}
